import React, { useCallback, useRef, useEffect, useState } from 'react'
import { connect } from 'react-redux'
import homeStyle from '../layout/home.scss'
import { getIfCollaseCol0OfActiveTabSelector, getIfCollaseCol1OfActiveTabSelector } from '../../selectors/baseSelector'
import { genSetCollapseColOfActiveTab } from '../../actions/home'

const maStateToProps = state => {
    return {
        ifActiveTabCollapseCol0: getIfCollaseCol0OfActiveTabSelector(state),
        ifActiveTabCollapseCol1: getIfCollaseCol1OfActiveTabSelector(state)
    }
}

const mapDispatchToProps = dispatch => {
    return {
        setActiveTabCollapse: (colIndex, collapse) => dispatch(genSetCollapseColOfActiveTab(colIndex, collapse)),
    }
}

export const ColHeader = connect(maStateToProps, mapDispatchToProps)((props) => {
    const [colIndex, setColIndex] = useState(0)
    const { title, setActiveTabCollapse } = props
    const collapseCol = isNaN(colIndex) ? false : props[`ifActiveTabCollapseCol${colIndex}`]

    const headerRef = useRef()

    const detectElParentClassName = useCallback(el => {
        if (el) {
            const parentEl = el.parentElement
            if (parentEl) {
                const parentElClassNames = (parentEl.getAttribute('class') || '').replace(/\s+/, ' ').split(' ')
                if (parentElClassNames.some(name => name.indexOf('col0') >= 0)) {
                    colIndex !== 0 && setColIndex(0)
                } else if (parentElClassNames.some(name => name.indexOf('col1') >= 0)) {
                    colIndex !== 1 && setColIndex(1)
                } else if (parentElClassNames.some(name => name.indexOf('content') >= 0)) {
                    setColIndex(NaN)
                } else {
                    parentEl.parentElement && detectElParentClassName(parentEl.parentElement)
                }
            }
        }
    }, [colIndex, setColIndex, setColIndex])

    useEffect(() => detectElParentClassName(headerRef.current), [headerRef])

    const wrapSetActiveTabCollapse = useCallback(() => setActiveTabCollapse(colIndex, !collapseCol), [colIndex, collapseCol])

    return (
        <div className={homeStyle.header} onClick={wrapSetActiveTabCollapse} ref={headerRef} title={isNaN(colIndex) ? '' : (collapseCol ? '点击展开' : '点击收缩')}>
            {title}
        </div>
    )
})